//
//  JSBookReaderManager.m
//  NiubilityProject
//
//  Created by Apple on 2018/5/24.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "JSBookReaderManager.h"
#import "JSReaderChapter.h"
#import "JSReaderBook.h"
#import "JSMarkModel.h"
#import "JSRenderConfig.h"

#define FONT_SIZE_KEY @"FONT_SIZE"
#define MAX_FONT_SIZE 20
#define MIN_FONT_SIZE 12

@interface JSBookReaderManager ()

@property (nonatomic, strong) dispatch_queue_t prepare_centen_queue;
@property (nonatomic, assign) CFRunLoopObserverRef observer;
@property (nonatomic, assign) BOOL duringLoadUp;
@property (nonatomic, assign) BOOL duringLoadNext;


@end;

@implementation JSBookReaderManager
- (instancetype)init{
    if (self = [super init]) {
        // 获取本地缓存字体大小信息
        NSUInteger fontSize = [[NSUserDefaults standardUserDefaults] integerForKey:FONT_SIZE_KEY];
        if (!fontSize) {
            fontSize = 16;
        }
        _BePrecached = @[].mutableCopy;
        // 0. 初始化队列
        _prepare_centen_queue = dispatch_queue_create("Prepare_conten_queue", DISPATCH_QUEUE_SERIAL);
        // 1. 获取配置信息
        [self getRenderConfig];
        
        
    }
    return self;
}
+ (JSBookReaderManager *)sharedJSBookReaderManager {
    static JSBookReaderManager *sharedJSBookReaderManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedJSBookReaderManager = [[self alloc] init];
    });
    return sharedJSBookReaderManager;
}
//MARK: 根据id获取整本书信息
/*
    根据书本id 获取浏览记录
 
 */
-(void)loadBookData:(NSInteger)bookId{
    
//    [JSReaderModel clearTable];
    if (!_curReaderModel) {
        JSReaderModel *readerM = [JSReaderModel findFirstByCriteria:[NSString stringWithFormat:@"WHERE bookID = %zd", bookId]];
        if (!readerM) {
            readerM = [[JSReaderModel alloc] init];
            readerM.bookID = bookId;
            readerM.fontSize = 16;
            readerM.lastPageIndex = 0;
            readerM.lastChapterIndex = 0;
            readerM.readOffset = 0;
            if([readerM save]){
                readerM = [JSReaderModel findFirstByCriteria:[NSString stringWithFormat:@"WHERE bookID = '%zd'", bookId]];
            };
        }
        // 保证存在主键
        _curReaderModel = readerM;
    }
    
    // 通过id 获取详细信息...
    
    if (!_curBook) {
        // 获取书本信息
        _curBook = [[JSReaderBook alloc]init];
        // test data
        _curBook.bookId = bookId;
        _curBook.bookName = @"Chapter";
        _curBook.totalChapter = 7;
        _curBook.curChpaterIndex = _curReaderModel.lastChapterIndex;
    }
    if ([self.contentDataDelegate respondsToSelector:@selector(reciveBookData:)]) {
        [self.contentDataDelegate reciveBookData:_curBook];
    }
}
//MARK:修改字体
- (void)increaseChangeSizeAction{
    if (self.curReaderModel.fontSize + 1 >= MAX_FONT_SIZE) return;
    self.curReaderModel.fontSize += 1;
    [self.curChapter parseChapterWithRenderSize:[self.contentDataSource renderSize] config:self.renderConfig];
}
- (void)decreaseChangeSizeAction{
    if (self.curReaderModel.fontSize - 1 < MIN_FONT_SIZE) return;
    self.curReaderModel.fontSize -= 1;
    [self.curChapter parseChapterWithRenderSize:[self.contentDataSource renderSize] config:self.renderConfig];
    
}
+ (void)saveFontSize:(CGFloat)fontSize{
    [[NSUserDefaults standardUserDefaults] setValue:@(fontSize) forKey:FONT_SIZE_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//获取上一页数据
-(JSReaderPager *)loadUpPageData:(JSReaderPageData)data{
    JSReaderPager *readerPage = nil;
    self.duringLoadUp = NO;
    self.duringLoadNext = NO;
    // 获取当前章节上一页数据 已缓存 可直接返回
    if (self.curReaderModel.lastPageIndex) {
//        self.duringLoadUp = YES;
        _duringReaderPagelIndex = self.curReaderModel.lastPageIndex - 1;
        readerPage = [self.curChapter chapterPagerWithIndex:_duringReaderPagelIndex];
        if (data) {  data(readerPage); }
        return readerPage;
        
    }else{
        
        // 获取上一章
        if ([self havePreChapter]) { // 是否有上一章
            self.duringLoadUp = YES; // 正在获取数据 根据切换是否完成 更新缓存
            
            if (self.prepareUpChapter.pageRangeArray.count) { // 是否有预缓存内容 直接缓存
                _duringReaderPagelIndex = self.prepareUpChapter.pageRangeArray.count - 1;
                _duringReaderChapterIndex = self.curReaderModel.lastChapterIndex-1;
                readerPage = [self.prepareUpChapter chapterPagerWithIndex:_duringReaderPagelIndex];
                return readerPage;
            }
            ////////////////////////////////////////////////////////////////////
            // 开始请求上一章数据
            ////////////////////////////////////////////////////////////////////
            if ([self.contentDataDelegate respondsToSelector:@selector(startRequestData)]) {
                [self.contentDataDelegate startRequestData];}
            _duringReaderChapterIndex = self.curReaderModel.lastChapterIndex - 1;
            [self skillToBook:self.curBook.bookId chapter:_duringReaderChapterIndex page:-1 pageData:data];
        }
    }
    return nil;
}
//获取下一页数据
-(JSReaderPager *)loadNextPageData:(JSReaderPageData)data{
    JSReaderPager *readerPage = nil;
    self.duringLoadNext = NO;
    self.duringLoadUp = NO;
    
    if (self.curReaderModel.lastPageIndex < self.curChapter.totalPage - 1) {
//        self.duringLoadNext = YES;
        _duringReaderPagelIndex = self.curReaderModel.lastPageIndex + 1;
        readerPage = [self.curChapter chapterPagerWithIndex:_duringReaderPagelIndex];

        if (data) { data(readerPage);}
        
        return readerPage;
        
    }else{
        // 获取下一章
        self.pageDataBlock = data;
        if ([self haveNextChapter]) {
            self.duringLoadNext = YES;
            _duringReaderPagelIndex = 0;
            _duringReaderChapterIndex = self.curReaderModel.lastChapterIndex + 1;

            if (self.prepareNextChapter.pageRangeArray.count) {
                readerPage = [self.prepareNextChapter chapterPagerWithIndex:_duringReaderPagelIndex];
                return readerPage;
            }
            ////////////////////////////////////////////////////////////////////
            // 开始请求下一章数据
            ////////////////////////////////////////////////////////////////////
            if ([self.contentDataDelegate respondsToSelector:@selector(startRequestData)]) {
                [self.contentDataDelegate startRequestData];}
            [self skillToBook:self.curBook.bookId chapter:_duringReaderChapterIndex page:0 pageData:data];
        }
    }
    return nil;
}
-(BOOL)havePreChapter{
    return self.curReaderModel.lastChapterIndex || self.curReaderModel.lastPageIndex;
}
-(BOOL)haveNextChapter{
    return !(self.curReaderModel.lastChapterIndex == self.curBook.totalChapter-1 && self.curReaderModel.lastPageIndex == self.curChapter.totalPage-1);
}

-(void)changeFinish{
    NSMutableDictionary *props = @{@"lastPageIndex":@(self.duringReaderPagelIndex),@"lastChapterIndex":@(self.duringReaderChapterIndex)}.mutableCopy;
    // 更新缓存
    [self.curReaderModel updataProps:props];

    if (self.duringLoadNext) {
        self.duringLoadNext = NO;
        JSReaderChapter *temp = self.curChapter;
        _curChapter = self.prepareNextChapter;
        _prepareNextChapter = nil;
        if (_curChapter.chapterIndex) {
            _prepareUpChapter = temp;
        }
    }
    if (self.duringLoadUp) {
         // 更新
        self.duringLoadUp = NO;
        JSReaderChapter *temp = self.curChapter;
        _curChapter = self.prepareUpChapter;
        _prepareUpChapter = nil;
        _prepareNextChapter = temp;
    }
    JSLog(@"aaaaa:%@", props);
    
}



//MARK:获取配置信息
-(void)getRenderConfig{
    _renderConfig = [JSRenderConfig findByPK:1];
    if (!_renderConfig) {
        _renderConfig = [JSRenderConfig new];
        _renderConfig.fontSize = 16;
        _renderConfig.rowMargin = 0;
        _renderConfig.kernMargin = 0;
        [_renderConfig save];
    }
}

/*
 //MARK: 第一次加载 根据 书本id 浏览记录 获取一页数据
 */
-(void)loadFromBook:(NSInteger)bookId PageData:(JSReaderPageData)data{
    [self skillToBook:bookId chapter:self.curReaderModel.lastChapterIndex page:self.curReaderModel.lastPageIndex pageData:data];
  
}
/**
 mark:pageIndex = -1, -> loading last Page info
 */
-(void)skillToBook:(NSInteger )bookId chapter:(NSInteger )chapterIndex page:(NSInteger)pageIndex pageData:(JSReaderPageData)data{
    // 1. 获取书本详细信息
    // 1.1 根据书本id 获取浏览记录 loadBookData 已经获取 curReanderModel
    [self loadBookData:bookId];
    
    // 2.通过index获取章节信息
    _curChapter = [self.curBook openBookWithChapter:chapterIndex];
    // 2.1 获取指定页信息
    
    dispatch_async(self.prepare_centen_queue, ^{
        [_curChapter parseChapterWithRenderSize:[self.contentDataSource renderSize] config:self.renderConfig];
        
        JSReaderPager *page = [_curChapter chapterPagerWithIndex:pageIndex != -1?pageIndex:_curChapter.pageRangeArray.count - 1];
        if (data) { data(page);}
        if ([self.contentDataDelegate respondsToSelector:@selector(recivePageData:isRenader:)]) {
            [self.contentDataDelegate recivePageData:page isRenader:YES];
        }
    });
}

#pragma mark - 注册RunLoop Observer
-(void)registerRunLoopObserver{
    CFRunLoopRef runLoop = CFRunLoopGetCurrent();
    CFStringRef runLooopModel = kCFRunLoopDefaultMode;
    self.observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
        if (activity == kCFRunLoopBeforeWaiting) {
            // code...
            [self startBeforehandTask:self.curReaderModel.lastChapterIndex prepareStyle:0];
        }
    });
    CFRunLoopAddObserver(runLoop, self.observer, runLooopModel);
}
-(void)cancelRunloopObserver{
    CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), self.observer, kCFRunLoopDefaultMode);
    CFRelease(self.observer); // 注意释放，否则会造成内存泄露
}
//MARK: 开始预缓存任务
/**
 0  : 全部加载
 -1 : 加载上一章
 1  : 加载下一章
 */
-(void)startBeforehandTask:(NSInteger )curChapterIndx prepareStyle:(NSInteger)style{
    if (!self.curBook) return;
    if (self.havePreChapter){
        if (curChapterIndx) {
            dispatch_async(self.prepare_centen_queue, ^{
                if (_prepareUpChapter.chapterIndex != curChapterIndx - 1) {
                    _prepareUpChapter = [self.curBook openBookWithChapter:curChapterIndx - 1];
                }
                if (!_prepareUpChapter) {
                    _prepareUpChapter = [self.curBook openBookWithChapter:curChapterIndx - 1];
                }
                if (!_prepareUpChapter.pageRangeArray.count) {
                    QMUILog(@"开始预缓存任务 上一章 : %zd^^^^^^^^^%zd --- %p", curChapterIndx, style,_prepareUpChapter);
                    [_prepareUpChapter parseChapterWithRenderSize:[self.contentDataSource renderSize] config:self.renderConfig];
                }
            });
                
        }
    }
    if (self.haveNextChapter){
        if (curChapterIndx >= self.curBook.totalChapter) { return; }
        dispatch_async(self.prepare_centen_queue, ^{
            
            if (_prepareNextChapter.chapterIndex != curChapterIndx + 1) {
                _prepareNextChapter = [self.curBook openBookWithChapter:curChapterIndx + 1];
            }
            if (!_prepareNextChapter.pageRangeArray.count) {
                
                QMUILog(@"开始预缓存任务 下一章 : %zd^^^^^^^^^%zd --- %p", curChapterIndx, style,_prepareUpChapter);

                [_prepareNextChapter parseChapterWithRenderSize:[self.contentDataSource renderSize] config:self.renderConfig];
            }
        });
        
    }
    
}






















/*
 
 //    if (self.havePreChapter && (!self.upChapter.pageRangeArray.count || self.nextChapter.chapterIndex != self.curChapter.chapterIndex +1))
 
 // 判断需要缓存的任务是否正在缓存或者已经缓存完成
 //    if (self.haveNextChapter && (!self.nextChapter.pageRangeArray.count || self.nextChapter.chapterIndex != self.curChapter.chapterIndex +1)) {
 
 */
/*
 //MARK: 根据index获取章节信息
 -(void)loadChapterData:(NSInteger)index{
 if ([self.contentDataDelegate respondsToSelector:@selector(startRequestData)]) {
 [self.contentDataDelegate startRequestData];
 }
 
 JSReaderChapter *chapter = [_curBook openBookWithChapter:index];
 // 解析章节文本信息
 _curRenderSize = [self.contentDataSource renderSize];
 [chapter parseChapterWithRenderSize:_curRenderSize config:self.renderConfig];
 _curChapter = chapter;
 
 if ([self.contentDataDelegate respondsToSelector:@selector(reciveChapterData:isRenader:)]){
 [self.contentDataDelegate reciveChapterData:chapter isRenader:!self.pageDataBlock];
 }
 if (index < self.curReaderModel.lastChapterIndex){ // 获取上一数据
 _duringReaderPagelIndex = chapter.totalPage - 1;
 
 }else if (index > self.curReaderModel.lastChapterIndex){
 _duringReaderPagelIndex = 0;
 }else if (index == self.curReaderModel.lastChapterIndex){
 [self reanderPageData:chapter mark:self.curReaderModel.lastPageIndex];
 return;
 }
 //    _duringReaderChapterIndex = index;
 [self reanderPageData:chapter mark:_duringReaderPagelIndex];
 
 
 }
 //MARK: 根据chapter 获取指定页面信息
 -(void)reanderPageData:(JSReaderChapter *)chapter mark:(NSInteger )pageIdex{
 JSReaderPager *pageData = [chapter chapterPagerWithIndex:pageIdex];
 if (self.pageDataBlock) {
 self.pageDataBlock(pageData);
 }
 if ([self.contentDataDelegate respondsToSelector:@selector(recivePageData:isRenader:)]) {
 [self.contentDataDelegate recivePageData:pageData isRenader:!self.pageDataBlock];
 }
 _pageDataBlock = nil;
 }
 -(void)loadOnLineChapterData:(NSURL *)url{
 if (!url) return;
 // 获取网络数据 解析
 if ([self.contentDataDelegate respondsToSelector:@selector(startRequestData)]) {
 [self.contentDataDelegate startRequestData];
 }
 
 JSReaderChapter *readerChapter = [[JSReaderChapter alloc]init];
 readerChapter.chapterIndex = 0;
 readerChapter.chapterContent = @"xxxxxx";
 [readerChapter parseChapterWithRenderSize:self.curRenderSize config:self.renderConfig];
 if ([self.contentDataDelegate respondsToSelector:@selector(reciveChapterData:isRenader:)]) {
 [self.contentDataDelegate reciveChapterData:readerChapter isRenader:!self.pageDataBlock];
 }
 
 }*/

@end
